import 'dart:convert';

import 'package:simple_barcode_scanner/simple_barcode_scanner.dart' deferred as sbs;
import 'package:syria_sports/core/network/internet_cubit.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:syria_sports/data/controllers/cp_controller.dart';

import '../../data/apiClient/api_client.dart';
import '../../data/models/sync_operation.dart';
import '../../data/remote/database_helper.dart';
import '../admin_home_tabs/coaches_tab/bloc/coaches_tab_cubit.dart';
import '../admin_home_tabs/coaches_tab/bloc/coaches_tab_screen.dart';
import '../admin_home_tabs/cp_tab/bloc/cp_cubit.dart';
import '../admin_home_tabs/cp_tab/bloc/cp_screen.dart';
import '../admin_home_tabs/other_tab/bloc/other_tab_cubit.dart';
import '../admin_home_tabs/other_tab/bloc/other_tab_screen.dart';
import '../admin_home_tabs/players_tab/bloc/players_tab_cubit.dart';
import '../admin_home_tabs/players_tab/players_tab_screen.dart';
import 'bloc/dashboard_container_bloc.dart';
import 'models/dashboard_container_model.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';

import "package:persistent_bottom_nav_bar/persistent_tab_view.dart";

class DashboardContainerScreen extends StatefulWidget {

  const DashboardContainerScreen({Key? key}) : super(key: key);


  static Widget builder(BuildContext context) {
    return BlocProvider<DashboardContainerBloc>(
        create: (context) => DashboardContainerBloc(DashboardContainerState(
            dashboardContainerModelObj: const DashboardContainerModel()))
          ..add(DashboardContainerInitialEvent()
          ),
        child: const DashboardContainerScreen());
  }

  @override
  State<DashboardContainerScreen> createState() => _DashboardContainerScreenState();
}

class _DashboardContainerScreenState extends State<DashboardContainerScreen> {
  final PersistentTabController _controller = PersistentTabController(
    initialIndex: 0
  );

  GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    mediaQueryData = MediaQuery.of(context);

    return SafeArea(
      child: MultiBlocProvider(
        providers: [
          BlocProvider<CPCubit>(
            create: (context) {
              return CPCubit()..init(InternetCubit.get(context).state == InternetState.connected);
            },
          ),
          BlocProvider<PlayersTabCubit>(
            create: (context) => PlayersTabCubit(PlayersTabInitial())..add(PlayerTabInitialEvent()),
          ),
          BlocProvider<CoachesTabCubit>(
            create: (context) => CoachesTabCubit()..init(),
          ),
          BlocProvider<OtherTabCubit>(
            create: (context) => OtherTabCubit()..init(),
          ),
        ],
        child: BlocBuilder<DashboardContainerBloc, DashboardContainerState>(
            builder: (context, state) {
              return Scaffold(
                body:PersistentTabView(
                  context,
                  controller: _controller,
                  onItemSelected: (value){
                    switch(value){
                      case 0:
                        //CPCubit.get(context).init(InternetCubit.get(context).state == InternetState.connected);
                      case 1:
                        //PlayersTabCubit.get(context).add(PlayerTabInitialEvent());
                      case 3:
                        //CoachesTabCubit.get(context).init();
                      case 4:
                        OtherTabCubit.get(context).init();
                    }
                  },
                  screens:[
                    const CPScreen(),
                    const PlayersTabScreen(),
                    Container(),
                    const CoachesTabScreen(),
                    const OtherTabScreen(),
                  ],
                  items: [
                    PersistentBottomNavBarItem(
                        icon: const Icon(Icons.home),
                        title: "لوحة التحكم",
                        activeColorPrimary: Colors.redAccent,
                        inactiveColorPrimary: Colors.grey,
                        inactiveColorSecondary: Colors.purple),
                    PersistentBottomNavBarItem(
                      icon: const Icon(Icons.group),
                      title: "اللاعبين",
                      activeColorPrimary: Colors.redAccent,
                      inactiveColorPrimary: Colors.grey,
                    ),
                    PersistentBottomNavBarItem(
                        icon: const Icon(Icons.qr_code_scanner,color: Colors.black,),
                        title: "الحضور",
                        activeColorPrimary: Colors.orange,
                        inactiveColorPrimary: Colors.grey,
                        onPressed: (value)async{
                          await sbs.loadLibrary();
                          if(APISData.homeData.exercise.isNotEmpty && APISData.homeData.exercise.first.exerciseId!= null) {
                            var res = await Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => sbs.SimpleBarcodeScannerPage(isShowFlashIcon: true,),
                                ));
                            
                            if(InternetCubit.get(context).state == InternetState.connected){
                              setState(() {
                                if (res is String && res != "-1") {
                                  CPController.addAttendance(res, APISData.homeData.exercise.first.exerciseId!).catchError((e){
                                    showErrorMessage(message: 'عذراً حدث خطأ ما الرجاء المحالة لاحقاً');
                                  }).then((value) {
                                    APISData.cpCubit.init(InternetCubit.get(context).state == InternetState.connected);
                                  });
                                }
                              });
                            }else{
                              print("\n\n\n\n");
                              var resLocale =await DatabaseHelper.insertSyncOperation(SyncOperation(
                                endpoint: ApiClient.attendance,
                                method: "POST",
                                payload: json.encode({
                                  'exercise_id':APISData.homeData.exercise.first.exerciseId,
                                  'barcode' : res,
                                  'datetime': DateTime.now().toIso8601String(),
                                }),
                                status: "pending",
                                createdAt: DateTime.now(),
                                updatedAt: DateTime.now(),
                              ));
                              print(resLocale);
                            }
                            
                            return;
                          } else{
                            var res = await Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => sbs.SimpleBarcodeScannerPage(isShowFlashIcon: true,),
                                ));
                            setState(() {
                              if (res is String && res != "-1") {
                                CPController.addAttendance(res, null).catchError((e){
                                  showErrorMessage(message: 'عذراً حدث خطأ ما الرجاء المحالة لاحقاً');
                                }).then((value) {
                                  APISData.cpCubit.init(InternetCubit.get(context).state == InternetState.connected);
                                });
                              }
                            });
                            return;
                          }
                        }
                    ),
                    PersistentBottomNavBarItem(
                      icon: const Icon(Icons.group),
                      title: "المدربين",
                      activeColorPrimary: Colors.redAccent,
                      inactiveColorPrimary: Colors.grey,
                    ),
                    PersistentBottomNavBarItem(
                      icon: const Icon(Icons.menu),
                      title: "المزيد",
                      activeColorPrimary: Colors.redAccent,
                      inactiveColorPrimary: Colors.grey,
                    ),
                  ],
                  resizeToAvoidBottomInset: true,
                  selectedTabScreenContext: ( context) {
                    //testContext = context;
                  },
                  backgroundColor: Theme.of(context).colorScheme.secondary,
                  //hideNavigationBar: _hideNavBar,
                  decoration: NavBarDecoration(
                    colorBehindNavBar:
                    Colors.transparent,
                    boxShadow: [
                      BoxShadow(color: Colors.grey,blurRadius: 3,spreadRadius: .6),
                    ],
                    borderRadius: BorderRadius.circular(2),
                  ),
                  // itemAnimationProperties: const ItemAnimationProperties(
                  //   duration: Duration(milliseconds: 0),
                  //   curve: Curves.ease,
                  // ),
                  // screenTransitionAnimation: const ScreenTransitionAnimation(
                  //   animateTabTransition: false,
                  // ),
                  navBarStyle: NavBarStyle.style15,
                ),
              );
            }),
      ),
    );
  }

}
